var _NORMAL = "0000000";
var layuiGridDataCache = [];

/**
 * 获取表格数据
 */
function getGridData(iary) {
    initGrid(); //重载表格
    var dataCate = $(".leftNav .layui-this a").text().substring(0, 4);

    if (iary === undefined) {
        iary = {
            data_cate : dataCate
        }
    }
    var inTrxObj = {
        trx_id          : 'XPBASICDATA',
        action_flg      : 'Q',
        iary            : [iary]
    };
    var outTrxObj = comTrxSubSendPostJson(inTrxObj);
    if(outTrxObj.rtn_code == _NORMAL) {
        layuiGridDataCache = outTrxObj.oary;
        _layuiGrid.f.setGridCols('layuiGrid', getTableCols());
        _layuiGrid.f.setGridData('layuiGrid', outTrxObj.oary);
    }
}

/**
 * 新增型号/规格-物料号数据对应关系
 */
function addGridData(iary) {
    if (iary === undefined) {
        iary = {}
    }
    var inTrxObj = {
        trx_id          : 'XPBASICDATA',
        action_flg      : 'A',
        iary            : [iary]
    };
    var outTrxObj = comTrxSubSendPostJson(inTrxObj);
    if(outTrxObj.rtn_code == _NORMAL) {
        layer.msg('新增型号/规格-物料号对应关系数据成功');
        getGridData();
    }
}

/**
 * 删除表格数据
 */
function deleteGridData(dataArrays) {
    if(0 === dataArrays.length) {
        layer.msg('没有需要删除的数据', function(){});
        return;
    }
    var iaryI = [];
    for(var i=0; i<dataArrays.length; i++){
        var rowData = dataArrays[i];
        var iary = {
            data_seq_id : rowData.dataSeqId,
            evt_user    : $("#userSpan").text()
        };
        iaryI.push(iary);
    }
    var inTrxObj = {
        trx_id     : 'XPBASICDATA',
        action_flg : 'D',
        iary       : iaryI
    };
    var outTrxObj = comTrxSubSendPostJson(inTrxObj);
    if(outTrxObj.rtn_code == _NORMAL) {
        layer.msg('数据删除成功');
        getGridData();
    }
}

/**
 * 修改表格数据
 */
function updateGridData(dataArrays) {
    if(0 === dataArrays.length) {
        layer.msg('没有需要修改的数据', function(){});
        return;
    }
    var iaryI = [];
    for(var i=0; i<dataArrays.length; i++){
        var iary = dataArrays[i];
        iary['evt_user'] = $("#userSpan").text();
        iaryI.push(iary);
    }
    var inTrxObj = {
        trx_id     : 'XPBASICDATA',
        action_flg : 'U',
        iary       : iaryI
    };
    var outTrxObj = comTrxSubSendPostJson(inTrxObj);
    if(outTrxObj.rtn_code == _NORMAL) {
        layer.msg('数据修改成功');
        getGridData();
    }
};

/**
 * 获取参数列设定
 */
function getTableCols() {
    var dataCate = $(".leftNav .layui-this a").text().substring(0, 4);
    if ("EFGR" === dataCate) {
        return [[
            {width:80, title: '复选框', type: 'checkbox'}
            ,{field:'operation', width:140, title: '操作',      toolbar:"#tableBar"}
            ,{field:'dataSeqId', width:150, title: 'dataSeqId', sort: true, hide: true}
            ,{field:'dataCate',  width:150, title: 'dataCate',  sort: true, hide: true}
            ,{field:'dataExt',   width:150, title: '分档版本',  sort: true, edit: true}
            ,{field:'dataId',    width:150, title: '单/多晶',   sort: true, edit: true}
            ,{field:'ext1',      width:150, title: '效率' ,     sort: true, edit: true}
            ,{field:'ext2',      width:150, title: 'Bin值',     sort: true, edit: true}
        ]];
    } else if ("ETTA" === dataCate) {
        return [[
            {width:80, title: '复选框', type: 'checkbox'}
            ,{field:'operation', width:140, title: '操作',      toolbar:"#tableBar"}
            ,{field:'dataSeqId', width:150, title: 'dataSeqId', sort: true, hide: true}
            ,{field:'dataCate',  width:150, title: 'dataCate',  sort: true, hide: true}
            ,{field:'dataId',    width:150, title: '年',        sort: true, edit: true}
            ,{field:'ext1',      width:150, title: '月' ,       sort: true, edit: true}
            ,{field:'ext2',      width:150, title: '目标效率值',sort: true, edit: true}
            ,{field:'ext3',      width:150, title: '单/多晶',   sort: true, edit: true}
        ]];
    } else if ("LIAT" === dataCate) {
        return [[
            {width:80, title: '复选框', type: 'checkbox'}
            ,{field:'operation', width:140, title: '操作',      toolbar:"#tableBar"}
            ,{field:'dataSeqId', width:150, title: 'dataSeqId', sort: true, hide: true}
            ,{field:'dataCate',  width:150, title: 'dataCate',  sort: true, hide: true}
            ,{field:'dataId',    width:150, title: '线别',      sort: true, edit: true}
            ,{field:'ext1',      width:150, title: '单/多晶' ,  sort: true, edit: true}
        ]];
    } else if ("MOMA" === dataCate) {
        return [[
            {width:80, title: '复选框', type: 'checkbox'}
            ,{field:'operation', width:140, title: '操作',      toolbar:"#tableBar"}
            ,{field:'dataSeqId', width:150, title: 'dataSeqId', sort: true, hide: true}
            ,{field:'dataCate',  width:150, title: 'dataCate',  sort: true, hide: true}
            ,{field:'dataId',    width:150, title: '型号/规格', sort: true, edit: true}
            ,{field:'ext1',      width:150, title: '物料号' ,   sort: true, edit: true}
        ]];
    } else if ("WIPV" === dataCate) {
        return [[
            {width:80, title: '复选框', type: 'checkbox'}
            ,{field:'operation', width:140, title: '操作',      toolbar:"#tableBar"}
            ,{field:'dataSeqId', width:150, title: 'dataSeqId', sort: true, hide: true}
            ,{field:'dataCate',  width:150, title: 'dataCate',  sort: true, hide: true}
            ,{field:'dataExt',   width:150, title: '统计时间',  sort: true, edit: true}
            ,{field:'dataId',    width:150, title: '型号/规格', sort: true, edit: true}
            ,{field:'ext1',      width:150, title: '工段' ,     sort: true, edit: true}
            ,{field:'ext2',      width:150, title: 'WIP值' ,    sort: true, edit: true}
        ]];
    } else {
        return [];
    }
}

/**
 * 初始化事件
 */
function initEvents() {
    //按钮功能提示框
    $("#query_btn").on('mouseover', function(){
        layer.tips('按条件查询数据 ', this, {
            tips: 1
        });
    });
    $("#delete_btn").on('mouseover', function(){
        layer.tips('删除选中行，或删除全部数据 ', this, {
            tips: 1
        });
    });
    $("#clean_btn").on('mouseover', function(){
        layer.tips('清空表格 ', this, {
            tips: 1
        });
    });
    $("#uploadModal_btn").on('mouseover', function(){
        layer.tips('导入Excel数据 ', this, {
            tips: 1
        });
    });
    $("#download_btn").on('mouseover', function(){
        layer.tips('下载Excel模板', this, {
            tips: 1
        });
    });
    $(".line_edit").on('mouseover', function(){
        layer.tips('编辑行数据后可点击保存 ', this, {
            tips: 1
        });
    });
    $(".line_del").on('mouseover', function(){
        layer.tips('删除当前行数据 ', this, {
            tips: 1
        });
    });

    //左侧导航点击事件
    $(".leftNav a").click(function () {
        layer.msg($(this).text());
        var dataCate = $(this).text().substring(0, 4);

        //清除Grid表格
        _layuiGrid.f.cleanGridCols('layuiGrid');
        _layuiGrid.f.cleanGridData('layuiGrid');
        $(".button_group a").hide();
        $("#query_btn").show();
        $("#delete_btn").show();
        $("#clean_btn").show();
        $("#uploadModal_btn").show();
        $("#download_btn").show();

        if ("EFGR" === dataCate) {
            // $("#uploadModal_btn").show();
            // $("#download_btn").show();
        }else if ("ETTA" === dataCate) {
            // $("#uploadModal_btn").show();
            // $("#download_btn").show();
        }else if ("LIAT" === dataCate) {
            // $("#uploadModal_btn").show();
            // $("#download_btn").show();
        }else if ("MOMA" === dataCate) {
            $("#add_btn").show();
        }else {
            $(".button_group a").hide();
        }
    });

    //查询按钮
    $("#query_btn").on('click', function () {
        var dataCate = $(".leftNav .layui-this a").text().substring(0, 4);
        if (dataCate === 'EFGR'){
            $("#queryEFGRModal input").val("");
            $("#queryEFGRModal select").val("");
            initSelect();
            $("#queryEFGRModalLabel").text("查询halm_效率Bin值对应关系数据");
            $("#queryEFGRModal").modal("show");
        }else {
            getGridData();
        }
    });

    //查询halm_效率Bin值对应关系数据
    $("#queryEFGRModal_btn").on('click', function(){
        var iary = {
            dataCate        : 'EFGR',
            dataExt         : $("#eff_no_select").val(),
            dataId	        : $("#ddj").val(),
            ext1            : $("#efficiency").val(),
            ext2            : $("#bin").val()
        };
        getGridData(iary);
        $("#queryEFGRModal").modal("hide");
    });

    //新增型号/规格-物料号模态框弹出
    $("#add_btn").on('click', function(){
        $("#model").val("");
        $("#material").val("");
        $("#addMOMAModalLabel").text("新增型号/规格-物料号对应关系数据");
        $("#addMOMAModal").modal("show");
    });

    //新增型号/规格-物料号
    $("#addMOMAModal_btn").on('click', function(){
        var iary = {
            dataCate        : 'MOMA',
            dataId	        : $("#model").val(),
            ext1            : $("#material").val(),
            evt_usr         : $("#userSpan").text()
        };
        addGridData(iary);
        $("#addMOMAModal").modal("hide");
    });

    //删除按钮
    $("#delete_btn").on('click', function () {
        layer.open({
            content: '是否确认删除?'
            , btn: ['删除选中行', '删除全部行', '取消']
            , btn1: function (index, layero) {
                var checkStatus = layui.table.checkStatus('layuiGrid');
                deleteGridData(checkStatus.data);
            }
            , btn2: function (index, layero) {
                //var tableData = layui.table.cache.layuiGrid; //只能获取到当前分页的table数据
                //deleteGridData(tableData);
                deleteGridData(layuiGridDataCache);
            }
            , btn3: function (index, layero) {

            }
        });
    });

    //清空按钮
    $("#clean_btn").on('click', function () {
        _layuiGrid.f.cleanGridData('layuiGrid');
    });

    //Excel上传模态框弹出
    $("#uploadModal_btn").on('click', function(){
        $("#fileinput").val("");
        $("#versionId").val("");
        $("#uploadModal").modal("show");
        $("#upload_btn").attr("disabled",false);
    });

    //Excel上传按钮
    $("#upload_btn").on('click', function(){
        var fileDir = $("#fileinput").val();
        var suffix = fileDir.substr(fileDir.lastIndexOf("."));
        if("" == fileDir){
            layer.msg('选择需要导入的Excel文件!', function(){});
            return false;
        }
        if(".xls" != suffix && ".xlsx" != suffix ){
            layer.msg('选择Excel格式的文件导入!', function(){});
            $('#fileinput').val("");
            return false;
        }

        var dataCate = $(".leftNav .layui-this a").text().substring(0, 4);

        if (dataCate !== null && dataCate !== '' && dataCate !== undefined) {
            $("#upload_btn").attr("disabled",true);
            $("#uploadForm").ajaxSubmit({
                url  : '/jz-report/uploadBisData.do',
                type : 'post',
                data : {
                    'dataCate' : dataCate,
                    'user'     : $("#userSpan").text()
                },
                success : function(data) {
                    $("#upload_btn").attr("disabled",false);
                    $("#uploadModal").modal("hide");
                    var outTrxObj = eval("("+data+")");
                    if(outTrxObj.rtn_code == _NORMAL){
                        layer.msg("Excel导入成功");
                        getGridData();
                    }else{
                        layer.msg(outTrxObj.rtn_mesg, function(){});
                    }
                }
            });
        }
    });

    //Excel模板导出按钮
    $("#download_btn").click(function (){
        var dataCate = $(".leftNav .layui-this a").text().substring(0, 4);
        generateBasicDataExcel(dataCate, "Report基础参数维护_" + $(".leftNav .layui-this a").text() + "_");
    });
}

/**
 * 初始化Grid表格
 */
function initGrid() {
    var options = _layuiGrid.f.getDefaultOptions('layuiGrid', '#test');
    layui.use('table', function(){
        layui.table.render(options);

        //监听工具条
        layui.table.on('tool(test)', function(obj){
            var data = obj.data;
            if(obj.event === 'detail'){
                layer.msg('ID：'+ data.id + ' 的查看操作');
            } else if(obj.event === 'del'){
                layer.confirm('是否删除行数据?', function(index){
                    deleteGridData([data]);
                    layer.close(index);
                });
            } else if(obj.event === 'edit'){
                updateGridData([data]);
            }
        });
    });
}

/**
 * 初始化Select
 */
function initSelect() {
    $("#eff_no_select").empty();
    var inTrxObj = {
        trx_id     : 'XPBASICDATA',
        action_flg : "Q",
        iary       : [{
            data_cate : 'EFGR'
        }]
    };
    var outTrxObj = comTrxSubSendPostJson(inTrxObj);
    if( outTrxObj.rtn_code == _NORMAL ) {
        $("#eff_no_select").append("<option ></option>");
        var arr = outTrxObj.oary;
        for(var i=0; i<arr.length; i++){
            for(var j=i+1; j<arr.length; j++){
                if(arr[i].dataExt==arr[j].dataExt){
                    arr.splice(j,1);
                    j--;
                }
            }
        }
        for(var i=0;i<arr.length;i++){
            if (arr[i].dataExt !== undefined) {
                $("#eff_no_select").append("<option value='" + arr[i].dataExt + "'>"+ arr[i].dataExt +"</option>");
            }
        }
    }
}

/**
 * 初始化
 */
function init() {
    layui.config({version: '1554720190412'}); //更新JS缓存
    layui.use('element', function(){}); //左侧导航初始化
    $(".button_group a").hide(); //按钮隐藏
    // $("select").select2({theme : "bootstrap"}); //下拉框样式
}


$(document).ready(function() {
    init();
    initSelect();
    initGrid();
    initEvents();
});
